<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 添加角色的按钮 -->
      <el-button type="primary" @click="addrole = true">添加角色</el-button>
      <!-- 列表 -->

      <el-table border :data="rolesList">
        <!-- 点击展开行 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- <pre>{{ scope.row.children }}</pre> -->
            <el-row
              v-for="(item, i) in scope.row.children"
              :key="item.id"
              :class="['bdbottom', i === 0 ? 'bdtop' : '']"
            >
              <!-- 一级 -->
              <el-col :span="5">
                <el-tag closable @close="delRightId(scope.row, item.id)">
                  {{ item.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, i1) in item.children"
                  :key="item2.id"
                  :class="[i1 === 0 ? '' : 'bdtop']"
                >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="delRightId(scope.row, item2.id)"
                    >
                      {{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="delRightId(scope.row, item3.id)"
                    >
                      {{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- index -->
        <el-table-column
          type="index"
          label="#"
          prop="date"
          width="180"
        ></el-table-column>
        <!-- 角色名称 -->
        <el-table-column
          :index="1"
          label="角色名称"
          prop="roleName"
          width="320"
        ></el-table-column>
        <!-- 角色描述 -->
        <el-table-column
          :index="1"
          label="角色描述"
          prop="roleDesc"
          width="320"
        ></el-table-column>
        <!-- 操作 -->
        <el-table-column :index="1" label="操作" prop="date">
          <template v-slot:default="scope">
            <!-- {{ scope.row }} -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editRoles(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delRoles(scope.row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-s-tools"
              size="mini"
              @click="tree(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加用户的弹框 -->
    <!-- :visible.sync显示隐藏 -->
    <el-dialog
      title="提示"
      :visible.sync="addrole"
      @close="dianlogClose"
      width="30%"
    >
      <!--  :before-close="handleClose" -->
      <!-- 表单 model列表的数据 rules验证规则 ref绑定的ref-->
      <!--

        v-model="" -->
      <el-form
        ref="addUserRef"
        :model="addRole"
        :rules="addRolesRules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 角色名称 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRole.roleName"></el-input>
        </el-form-item>
        <!-- 角色描述 -->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addrole = false">取 消</el-button>
        <el-button type="primary" @click="addRoles()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑的弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="etitRole"
      @close="dianlogClose"
      width="30%"
    >
      <el-form
        ref="addUserRef"
        :model="edit"
        :rules="addRolesRules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <!-- 角色名称 -->
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="edit.roleName"></el-input>
        </el-form-item>
        <!-- 角色描述 -->
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="edit.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="etitRole = false">取 消</el-button>
        <el-button type="primary" @click="edits()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限的弹框 -->
    <el-dialog
      title="提示"
      :visible.sync="distDialog"
      width="50%"
      @close="defClose"
    >
      <!-- 树装图 -->
      <!-- data为列表数据 props配置选项树形控件的属性绑定对象
      node-click节点被点击时的回调
      -->
      <el-tree
        :data="treeList"
        :props="treeProps"
        default-expand-all
        show-checkbox
        :default-checked-keys="defkey"
        node-key="id"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="distDialog = false">取 消</el-button>
        <el-button type="primary" @click="def()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import http from '../util/http'
export default {
  data () {
    return {
      // 角色列表的数据
      rolesList: [],
      // 添加用户弹框
      addrole: false,
      // 编辑用户的弹框
      etitRole: false,
      // 分配角色
      distDialog: false,
      // 添加的数据
      addRole: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑的数据
      edit: {
        roleName: '',
        roleDesc: '',
        id: ''
      },
      // 分配角色的数据
      treeList: [],
      // 配置选项树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认勾选的key值的id
      defkey: [],
      // 角色的id
      // defId: "",
      // 添加的规则
      addRolesRules: {
        roleName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 10,
            message: '长度在 2 到 10 个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    // 当dom挂载完成调用请求数据的函数
    this.roles()
  },
  methods: {
    // 获取列表
    roles () {
      http('roles').then((res) => {
        // console.log(res.data.data);
        this.rolesList = res.data.data
      })
    },
    // 添加用户
    addRoles () {
      http({
        url: 'roles',
        method: 'post',
        data: this.addRole
      }).then((res) => {
        console.log(res.data.meta.status)
        if (res.data.meta.status === 201) {
          this.$message.success('添加成功')
          this.addrole = false
          this.roles()
        } else {
          this.$message.error('添加失败')
        }
      })
    },
    // 关闭弹窗清空输入框
    dianlogClose () {
      this.$refs.addUserRef.resetFields()
    },
    // 删除用户
    delRoles (id) {
      // console.log(id.id);
      const a = confirm('确定要真实删除此用户吗')
      if (a) {
        http.delete(`roles/${id.id}`).then((res) => {
          // console.log(res.data.meta.status);
          if (res.data.meta.status === 200) {
            this.$message.success('删除成功')
            this.roles()
          } else {
            this.$message.erroe('删除失败')
          }
        })
      }
    },
    // 编辑用户
    editRoles (val) {
      this.etitRole = true
      // console.log(val);
      this.edit.roleName = val.roleName
      this.edit.roleDesc = val.roleDesc
      this.edit.id = val.id
    },
    // 确定编辑
    edits () {
      this.etitRole = false
      http({
        url: `roles/${this.edit.id}`,
        method: 'put',
        data: this.edit
      }).then((res) => {
        // console.log(res.data.meta.status);
        if (res.data.meta.status === 200) {
          this.$message.success('编辑成功')
          // this.roles();
          this.roles()
        }
      })
    },
    // 分配权限
    // 通过id查询用户

    // 根据Id删除对应的权限
    async delRightId (role, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }
      const { data: res } = await http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }
      // this.getRolesList()
      role.children = res.data
    },

    // 点击分配权限加载全部权限的数据
    tree (row) {
      this.roleId = row.id
      console.log(this.roleId)
      http('rights/tree').then((res) => {
        // console.log(res.data.data);
        this.treeList = res.data.data
      })
      this.getDefkey(row, this.defkey)
      this.distDialog = true
      console.log(this.defkey)
    },
    // 递归，获取角色使用三级权限id，并保存到defkey
    // 传两个值 一个是节点 另外一个数组
    getDefkey (node, arr) {
      // 如果没有children就是三级角色
      if (!node.children) {
        return arr.push(node.id)
      }
      // 不是的话就遍历
      node.children.forEach((item) => {
        this.getDefkey(item, arr)
      })
    },
    // 关闭分配权限的时候
    defClose () {
      this.defkey = []
    },
    // 确定分配
    def () {
      this.distDialog = false
      // getCheckedKeys 获取目前被选中的节点所组成的数组
      // getHalfCheckedKeys 获取目前半选中
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      // console.log(keys.join(","));

      const rids = keys.join(',')
      http({
        method: 'post',
        url: `roles/${this.roleId}/rights`,
        data: { rids }
      }).then((res) => {
        console.log(res.data)
        if (res.data.meta.status === 200) {
          this.$message.success('分配成功')
          this.roles()
        }
      })
    }
  }
}
</script>
